import store from '@/store';
import prenv from '../prenv';
import storage from './storage';
import { getUuid, isEmpty, getAppId } from './utils';
import { loginWxinfoHandler } from '@/hooks';

/**
 * 小程序埋点
 * @returns {}
 */
export function useTrace() {
    let __traceStartTime = '';
    let __traceEndTime = '';
    let __eventData = {};
    let __eventId = '';

    /**
     * 页面停留时长开始时间记录
     */
    const traceStart = () => {
        setTimeout(() => {
            const appStatus = store.useAppStatusStore();
            if (appStatus.onShow === 1 && __traceStartTime == '') {
                __traceStartTime = +new Date();
            }
        }, 100);
    };

    /**
     * 页面停留时长离开时间记录
     */
    const traceStay = () => {
        setTimeout(() => {
            const appStatus = store.useAppStatusStore();
            if (appStatus.onHide === 1) {
                appStatus.onHide = 0;
            } else {
                __traceEndTime = +new Date();
                const stayTime = __traceEndTime - __traceStartTime;
                __traceStartTime = '';
                send({
                    eventId: __eventId,
                    eventType: 'stay',
                    eventData: Object.assign({ duration: Math.round((stayTime / 1000) * 10) / 10 }, __eventData)
                });
            }
        }, 100);
    };

    /**
     * 页面访问次数 PV
     * @param {*} eventType
     */
    const traceLoad = (eventId = '', eventData = {}, eventType = 'load') => {
        __eventId = eventId;
        __eventData = eventData;
        send({ eventId, eventData, eventType });
    };

    /**
     * 点击事件上报
     * @param {*} eventId 点击事件ID
     * @param {*} eventData
     * @param {*} eventType
     */
    const traceReport = (eventId = '', eventData = {}, eventType = 'click') => {
        send({
            eventId,
            eventData,
            eventType
        });
    };

    /**
     * 发送上报
     * @param {*} params
     */
    const send = async params => {
        const currentEnv = store.useEnvStore().currentEnv;
        const url = prenv[currentEnv]['API_BASE_URL']['apigw'] + '/miniapp/behaviour/add';
        const userId = storage.get('userId');

        const currentRoutes = getCurrentPages();
        const currentRoute = currentRoutes[currentRoutes.length - 1];
        const path = currentRoute.route;

        const shopId = storage.get('ZW_SHOP_ID');
        const tenantId = storage.get('ZW_TENANT_ID');
        const reportTime = Date.now();

        const {
            deviceId,
            deviceType,
            deviceBrand,
            deviceModel,
            deviceOrientation,
            devicePixelRatio,
            osName,
            osVersion,
            osLanguage,
            osTheme,
            hostName,
            hostVersion,
            wifiEnabled,
            appId,
            appVersion
        } = uni.getSystemInfoSync();
        const os = JSON.stringify({
            deviceId,
            deviceType,
            deviceBrand,
            deviceModel,
            deviceOrientation,
            devicePixelRatio,
            osName,
            osVersion,
            osLanguage,
            osTheme,
            wifiEnabled,
            hostName,
            hostVersion
        });

        let openid = storage.get('openid');
        let unionid = storage.get('unionid');

        if (isEmpty(openid) || isEmpty(unionid)) {
            const res = await loginWxinfoHandler();
            openid = res.openid;
            unionid = res.unionid;
        }

        const options = {
            appId: appId || getAppId(),
            appVersion,
            userId,
            shopId,
            tenantId,
            openid,
            unionid,
            uuid: getUuid(),
            reportTime,
            source: 'applet',
            env: 'applet',
            runtimeEnv: currentEnv,
            channel: '1',
            path,
            os,
            browser: '',
            eventId: '',
            eventData: {},
            eventType: ''
        };

        const data = Object.assign({}, options, params);
        data.eventData = JSON.stringify(data.eventData);

        uni.request({
            url,
            method: 'POST',
            data
        });
    };

    return {
        traceStart,
        traceStay,
        traceLoad,
        traceReport
    };
}
